package com.ygqh.baby.controller.utils;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 读取Excel
 *
 * @author: sunshuo
 * @date: 2018/12/11 16:54
 */
public class ExcelUtil {

	public static List<Map<Integer, Object>> readExcel(MultipartFile uploadFile) throws IOException {
		InputStream is = uploadFile.getInputStream();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		//只读取第一个sheet
		XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
		if (xssfSheet == null) {
			return null;
		}
		// Read the Row
		int rownums = xssfSheet.getPhysicalNumberOfRows();
		List<Map<Integer, Object>> list = new ArrayList<>(rownums);

		for (int rowNum = 1; rowNum <= rownums; rowNum++) {
			XSSFRow xssfRow = xssfSheet.getRow(rowNum);
			if (xssfRow != null) {
				//列数量
				int columns = xssfRow.getLastCellNum();
				Map<Integer, Object> map = new HashMap<>(columns);
				for (int c = 0; c < columns; c++) {
					try {
						map.put(c, getValue(xssfRow.getCell(c)));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				list.add(map);
			}
		}
		return list;
	}

	private static Object getValue(XSSFCell hssfCell) {
		if (hssfCell == null)
			return null;
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			return hssfCell.getNumericCellValue();
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}
}
